package com.cloudkinto.controller.orderback;


import com.cloudkinto.common.annotations.UserSessionRequired;
import com.cloudkinto.common.utils.TimeUtils;
import com.cloudkinto.service.orderback.vo.*;
import com.cloudkinto.service.orderinput.vo.OrderInputAddReq;
import com.cloudkinto.service.product.ProductInfoService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.cloudkinto.service.orderback.OrderBackService;

import com.cloudkinto.common.web.PageResult;
import com.cloudkinto.common.web.SingleResult;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cloudkinto.base.BaseController;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhangyy
 * @since 2020-08-05
 */
@RestController
@Api(tags = "退货截单模块")
@RequestMapping("/api/orderBack")
public class OrderBackController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(OrderBackController.class);

    @Autowired
    private OrderBackService service;
    @Autowired
    private ProductInfoService productInfoService;

    @UserSessionRequired
    @GetMapping("/addInit")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult addInit() {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return service.addInit(userId, companyId);
    }

    @UserSessionRequired
    @PostMapping("")
    @ApiOperation(value = "新增", notes = "新增")
    public SingleResult add(@RequestBody @Validated OrderBackAddReq req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return SingleResult.success("新增成功", service.add(req, userId, companyId));
    }

//    @UserSessionRequired
//    @PostMapping("processorStorage")
//    @ApiOperation(value = "仓库处理", notes = "新增")
//    public SingleResult processorStorage(@RequestBody @Validated OrderBackProcessorStorageReq req) {
//        Long userId = getCurrentUserId();
//        Long companyId = getCompanyId();
//        service.processorStorage(req, userId, companyId);
//        return SingleResult.success( );
//    }

    @UserSessionRequired
    @PostMapping("customerProcessing")
    @ApiOperation(value = "顾客处理", notes = "顾客处理")
    public SingleResult customerProcessing(@RequestBody @Validated OrderBackCustomerProcessingReq req) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        service.customerProcessing(req, userId, companyId);
        return SingleResult.success();
    }

    @UserSessionRequired
    @GetMapping("/updateInit/{id}")
    @ApiOperation(value = "编辑初始化", notes = "编辑初始化")
    public SingleResult updateInit(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        Long companyId = getCompanyId();
        return service.updateInit(id, userId, companyId);
    }

    @UserSessionRequired
    @PutMapping("")
    @ApiOperation(value = "修改", notes = "修改")
    public SingleResult update(@RequestBody @Validated OrderBackUpdateReq req) {
        Long userId = getCurrentUserId();
        return SingleResult.success("修改成功", service.update(req, userId));
    }

    @UserSessionRequired
    @DeleteMapping("/{id}")
    @ApiOperation(value = "根据id删除", notes = "根据id删除")
    public SingleResult delete(@PathVariable("id") Long id) {
        Long userId = getCurrentUserId();
        return SingleResult.success("删除成功", service.delete(id, userId));
    }

    @UserSessionRequired
    @GetMapping("/{id}")
    @ApiOperation(value = "根据id查看详情", notes = "根据id查看详情")
    public SingleResult detail(@PathVariable("id") Long id) {
        return SingleResult.success("查询成功", service.detail(id));
    }


    @UserSessionRequired
    @GetMapping("/pageInit")
    @ApiOperation(value = "查询初始化", notes = "查询初始化")
    public SingleResult pageInit() {
        return service.pageInit(getShopId(), getCompanyId(), getCurrentUserId());
    }

//    @GetMapping("/list")
//    @ApiOperation(value = "查询", notes = "查询")
//    public SingleResult list(HttpServletRequest request){
//        Long companyId = getCompanyId();
//
//        Map<String, String> map = new HashMap<>();
//        String keyword = request.getParameter("keyword");
//        map.put("keyword", keyword);
//        return SingleResult.success("查询成功", service.getList(map));
//    }

    @UserSessionRequired
    @GetMapping("/listPage")
    @ApiOperation(value = "查询（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "status", value = "状态"),
            @ApiImplicitParam(name = "result", value = "结果"),
            @ApiImplicitParam(name = "datType", value = "0 创建日期（默认） 1 到货日期"),
            @ApiImplicitParam(name = "sDate", value = "开始时间"),
            @ApiImplicitParam(name = "eDate", value = "结束时间"),
            @ApiImplicitParam(name = "unclaimed", value = "无人认领标志 传：1 只显示无人认领的退货"),
            @ApiImplicitParam(name = "applyExtension", value = "申请延期 0 未申请 1申请中 2申请成功 3 未同意"),

            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "keyword", value = "关键字（模糊查询）"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")})
    public PageResult listPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String unclaimed = request.getParameter("unclaimed");

        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        String status = request.getParameter("status");
        String result = request.getParameter("result");
        String datType = request.getParameter("datType");
        String sDate = request.getParameter("sDate");
        String eDate = request.getParameter("eDate");
        String applyExtension = request.getParameter("applyExtension");
        if (StringUtils.isNotBlank(applyExtension)) {
            map.put("applyExtension", applyExtension);
        }
        if (StringUtils.isNotBlank(unclaimed)) {
            map.put("unclaimed", unclaimed);
        }
        map.put("keyword", keyword);
        map.put("current", current);
        map.put("status", status);
        map.put("result", result);
        map.put("datType", datType);
        if (StringUtils.isNotBlank(sDate))
            map.put("sDate", sDate);
        if (StringUtils.isNotBlank(eDate))
            map.put("eDate", TimeUtils.addDaysFormat(eDate, "yyyy-MM-dd", 1));
        if (getShopId() != null)
            map.put("shopId", getShopId() + "");
        map.put("pageSize", size);
        map.put("companyId", companyId + "");
        return service.getListPage(map);
    }

    @UserSessionRequired
    @GetMapping("/productListPage")
    @ApiOperation(value = "商品（分页）", notes = "查询（分页）")
    @ApiImplicitParams({@ApiImplicitParam(name = "productType", value = "产品类型"),
            @ApiImplicitParam(name = "current", value = "当前页"),
            @ApiImplicitParam(name = "keyword", value = "关键字（模糊查询）"),
            @ApiImplicitParam(name = "pageSize", value = "页面大小")})
    public PageResult productListPage(HttpServletRequest request) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String productType = request.getParameter("productType");
        String current = request.getParameter("current");
        String size = request.getParameter("pageSize");
        map.put("companyId", String.valueOf(companyId));
        map.put("productType", productType);
        map.put("keyword", keyword);
        map.put("current", current);
        map.put("pageSize", size);
        return productInfoService.getListPage(map);
    }

    @UserSessionRequired
    @GetMapping("/productType")
    @ApiOperation(value = "新增初始化", notes = "新增初始化")
    public SingleResult productType() {
        return service.productType();
    }


    @UserSessionRequired
    @GetMapping("/unclaimed")
    @ApiOperation(value = "认领接口", notes = "认领接口")
    public SingleResult unclaimed(Long id) {
        Long companyId = getCompanyId();
        service.unclaimed(id, companyId);
        return SingleResult.success("认领成功", "");
    }

    @UserSessionRequired
    @GetMapping("/settag/init")
    @ApiOperation(value = "设置标签初始化", notes = "设置标签初始化")
    public SingleResult settagInit() {
        Long companyId = getCompanyId();
        return SingleResult.success(service.settagInit(companyId));
    }

    @UserSessionRequired
    @PostMapping("/settag")
    @ApiOperation(value = "设置标签", notes = "设置标签")
    public SingleResult settag(@RequestBody OrderBackSetTag tag) {
        service.settag(tag, getCurrentUserId(), getCompanyId());
        return SingleResult.success();
    }


    @UserSessionRequired
    @PostMapping("/importFileForBack")
    @ApiOperation(value = "导入退货单", notes = "导入退货单")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = ErrorMsg.class))
    public SingleResult importFileForBack(MultipartFile file) {
        Long userid = getCurrentUserId();
        List<ErrorMsg> list = service.importFileForBack(file, userid, getCompanyId());
        return SingleResult.success(list);
    }


    @UserSessionRequired
    @GetMapping("/exportBackOrder")
    @ApiOperation(value = "导出退货单", notes = "导入退货单")
    @ApiResponses(@ApiResponse(code = 200, message = "", response = ErrorMsg.class))
    public void exportBackOrder(HttpServletRequest request, HttpServletResponse response) {
        Long companyId = getCompanyId();

        Map<String, String> map = new HashMap<>();
        String keyword = request.getParameter("keyword");
        String unclaimed = request.getParameter("unclaimed");

        String status = request.getParameter("status");
        String result = request.getParameter("result");
        String datType = request.getParameter("datType");
        String sDate = request.getParameter("sDate");
        String eDate = request.getParameter("eDate");
        String applyExtension = request.getParameter("applyExtension");
        if (StringUtils.isNotBlank(applyExtension)) {
            map.put("applyExtension", applyExtension);
        }
        if (StringUtils.isNotBlank(unclaimed)) {
            map.put("unclaimed", unclaimed);
        }
        map.put("keyword", keyword);
        map.put("status", status);
        map.put("result", result);
        map.put("datType", datType);
        if (StringUtils.isNotBlank(sDate))
            map.put("sDate", sDate);
        if (StringUtils.isNotBlank(eDate))
            map.put("eDate", TimeUtils.addDaysFormat(eDate, "yyyy-MM-dd", 1));
        if (getShopId() != null)
            map.put("shopId", getShopId() + "");
        map.put("companyId", companyId + "");
        service.exportBackOrder(map,response);
    }

    @UserSessionRequired
    @PostMapping("/downErrorMsgList")
    @ApiOperation(value = "下载importFileForBack 错误信息")
    public void downErrorMsgList(@RequestBody List<ErrorMsg> msgList, HttpServletResponse response) {
        service.downErrorMsgList(msgList, response);
    }


    @UserSessionRequired
    @GetMapping("/getBackCode")
    @ApiOperation(value = "获取退货码列表")
    public SingleResult getBackCode() {
        return SingleResult.success(service.getBackCode(getCompanyId()));
    }


    @UserSessionRequired
    @GetMapping("/applyExtension")
    @ApiOperation(value = "申请延期")
    public SingleResult applyExtension(Long id) {
        service.applyExtension(id, getCurrentUserId());
        return SingleResult.success();
    }

}

